/**
 * 
 */
package com.google.code.jkippt.parser;

import java.io.IOException;


import com.google.code.jkippt.http.paging.Meta;
import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;

/**
 * Result Page parser.
 * @author Federico De Faveri defaveri@gmail.com
 */
public class PageParser<T> {

	protected Gson gson;
	protected JsonReader reader;
	protected Class<T> type;
	protected boolean firstObject;
	protected boolean metaConsumed;

	public PageParser(Gson gson, JsonReader reader, Class<T> type) throws ParserException {
		this.gson = gson;
		this.reader = reader;
		this.type = type;
		this.firstObject = true;
		this.metaConsumed = false;
		
		init();
	}

	protected void init() throws ParserException
	{
		try {
			reader.beginObject();
		} catch (IOException e) {
			throw new ParserException("Parsing error", e);
		}
	}

	/**
	 * Returns the Meta area from the page.
	 * @return
	 * @throws ParserException
	 */
	public Meta getMeta() throws ParserException
	{
		if (metaConsumed) throw new IllegalStateException("Meta element already requested.");
		metaConsumed = true;
		try {
			reader.nextName();
			return gson.fromJson(reader, Meta.class);
		} catch (IOException e) {
			throw new ParserException("Parsing error", e);
		}
	}

	/**
	 * Checks if there are more objects in the page.
	 * @return
	 * @throws ParserException
	 */
	public boolean hasMoreObjects() throws ParserException
	{
		try {
			if (firstObject) {
				beginObjects();
				firstObject = false;
			}
			return reader.hasNext();
		} catch (IOException e) {
			throw new ParserException("Parsing error", e);
		}
	}

	/**
	 * Returns the next object in the page.
	 * @return
	 * @throws ParserException
	 */
	public T nextObject() throws ParserException {
		if (!hasMoreObjects()) throw new IllegalStateException("There are no more objects");
		return gson.fromJson(reader, type);
	}

	protected void beginObjects() throws IOException
	{
		reader.nextName();
		reader.beginArray();

	}

}
